import Base64 from 'js-base64'
import AdminSerivce from 'src/service/admin'

export default {
  data() {
    return {
      params: {},
      action: '',
    }
  },
  props: {
    type: {
      type: String,
      default: "pic"
    },
    supportTypes: {
      type: Array,
      default: ["image/png", "image/jpeg"]
    },
    maxSize: {
      type: Number,
      default: 5
    }
  },
  methods: {
    beforeUpload: function (file) {
      const me = this;
      const support = this.supportTypes.filter(d => {
        return file.type === d;
      });

      if (support.length == 0) {
        me.$message.error("上传的文件类型不对，请上传指定的文件格式。")
        return false;
      }
      const isLt = file.size / 1024 / 1024 < 5;

      if (!isLt) {
        this.$message.error('上传的文件大小超过了限制!请修改图片的大小。');
        return false;
      }
      return new Promise(function (resolve, reject) {
        me.buildRequestParams(file, me.owner).then(ds => {
          me.params = ds;
          me.action = me.params['host'];
          me.$nextTick(function () {
            resolve();
          })
        }).catch(function (e) {
          reject(e);
        });
      })
    },
    buildCallbackBody: function (dir, file, dirpath, ext, owner) {
      const protocol = window.location.protocol
      const host = window.location.host
      const callbackUrl = protocol + '//' + host + '/api/public/upload/callback';
      //const callbackUrl = "https://www.hwlcn.com/api/public/upload/callback";
      const callbackParams = '{"bucket":${bucket},"object":${object},"etag":${etag},"type":"' + this.type + '","mimeType":${mimeType},"size":${size},"fileName":\"' + file.name + '\","dir":\"' + dir + '\","dirPath":\"' + dirpath + '\","ext":\"' + ext + '\",' +
        '"owner":"' + owner + '"}';
      const callbackBody = {
        'callbackUrl': callbackUrl,
        'callbackBody': callbackParams,
        'callbackBodyType': 'application/json'
      }
      const callbackJson = JSON.stringify(callbackBody)
      return Base64.Base64.encode(callbackJson)
    },
    get_suffix(filename) {
      const pos = filename.lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) {
        suffix = filename.substring(pos + 1)
      }
      return suffix
    },
    onProgress: function (event, file, fileList) {

    },
    buildRequestParams: async function (file, owner) {
      const datas = await AdminSerivce.aliyunOssPolicy()
      const data = datas.datas[0]
      const suffix = this.get_suffix(file.name)
      const callback = this.buildCallbackBody(data['dir'], file, data['dirPath'], suffix, owner)
      return {
        'key': data['key'] + '.' + suffix,
        'policy': data['policy'],
        'OSSAccessKeyId': data['OSSAccessKeyId'],
        'success_action_status': data['success_action_status'], //让服务端返回200,不然，默认会返回204
        'signature': data['signature'],
        'callback': callback,
        'expire': data['expire'],
        'host': data['host']
      }
    }

  }

}
